using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.InputSystem;
using UnityEngine.UIElements;

public class PlayerManager : MonoBehaviour
{
    private Rigidbody2D rb2D;
    public float moveSpeed = 1;
    public ScoreManager scoreManager;
    public InputManager inputManager;
    private SavePoint savePoint;
    public AudioSource audioSource;
    public List<AudioClip> clipList;
    public float direction;
    // Start is called before the first frame update
    void Start()
    {
        rb2D = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        rb2D.velocity = new Vector2(direction * moveSpeed, rb2D.velocity.y);
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "SavePoint")
        { 
            SavePoint colliderSavePoint = collision.gameObject.GetComponent<SavePoint>();
            if(colliderSavePoint != null && colliderSavePoint != savePoint) 
            { 
                savePoint = colliderSavePoint;
                savePoint.BecameRealSavePoint();
                audioSource.PlayOneShot(clipList[0]);
            }
        }
        else if(collision.gameObject.tag =="Spike")
        {
            BackToSavePoint();
            audioSource.PlayOneShot(clipList[1]);
        }
        else if( collision.gameObject.tag == "Coin")
        {
            audioSource.PlayOneShot(clipList[2]);
            scoreManager.ChangeScore(10);
            collision.enabled = false;
        }
    }
    public void BackToSavePoint()
    {
        if(savePoint != null)
        transform.position = savePoint.transform.position + new Vector3( 0, 0.5f ,0);
    }

    private void OnEnable()
    {
        inputManager.inputDirectionAction.performed += OnDirectionAction;
    }
    private void OnDisable()
    {
        inputManager.inputDirectionAction.performed -= OnDirectionAction;
    }


    public void OnDirectionAction(InputAction.CallbackContext context)
    {
        direction = context.ReadValue<float>();
    }
}
